<script lang="ts" setup>
import { useRouter } from 'vue-router';
import { useFetch } from '@/home/hooks/fetch';
import { useAsyncData } from '@/home/hooks/async-data';
import { useTitleForClient } from '@/home/hooks/browser';
import { useI18n } from 'vue-i18n';
import Journalism from './components/Journalism.vue';
import { formatNumber } from '@/home/utils/format';
import bgImage from '@/home/assets/column/bg.jpg';

const props = defineProps({
  id: {
    type: String,
    default: '',
  },
});

const router = useRouter();
const { setTitle } = useTitleForClient();
const { t } = useI18n();

const generateTitle = (title: string) => `${title} - ${t('home.column.index.title')}`;

const { $fetch } = useFetch();
const { data: detail } = useAsyncData(
  'column:detail',
  () => $fetch('/popSpecialColumn/getColumnDetail', {
    method: 'post',
    data: {
      columnId: props.id,
    },
  }),
  {
    watch: [() => props.id],
    onAfterHandle({ handleSuccess, serverContext, data }) {
      if (serverContext) {
        if (handleSuccess && data?.productId) {
          serverContext.title = generateTitle(data.title);
          serverContext.description = data.desc;
        }
        else {
          // 如果请求出错直接服务器重定向到 404 页面
          serverContext.redirect = '/404';
        }
      }
      else {
        if (handleSuccess && data?.productId) {
          setTitle(generateTitle(data.title));
        }
        else {
          router.replace('/404');
        }
      }
    },
  },
);
</script>

<template>
  <main class="page-column">
    <section class="h-300 bg-white bg-cover bg-no-repeat" :style="{ 'background-image': `url(${detail.coverUrl || bgImage})` }" v-if="detail">
      <div class="mx-auto max-w-900 pt-70 text-#292929">
        <h1 class="line-clamp-1 break-anywhere text-center text-balance text-32 font-semibold leading-40">
          {{ detail.title }}
        </h1>

        <p class="line-clamp-2 mt-24 min-h-48 text-center text-14 leading-24">
          {{ detail.desc }}
        </p>

        <div class="mt-24 flex-y-center justify-center gap-x-32 text-14 text-#575757 leading-22">
          <div>{{ $t('home.column.index.infoTotal', { total: formatNumber(detail.infoNum) }) }}</div>
          <div>{{ $t('home.column.index.like', { total: formatNumber(detail.likeCount) }) }}</div>
          <div>{{ $t('home.column.index.view', { total: formatNumber(detail.viewCount) }) }}</div>
        </div>
      </div>
    </section>

    <section class="mx-auto mt-42 max-w-900">
      <Journalism type="column" :query="props.id" />
    </section>
  </main>
</template>

<style lang="scss" scoped>
</style>
